package com.dlb.andorid.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dlb.andorid.R;
import com.dlb.andorid.XContract;
import com.dlb.andorid.XServerMsg;
import com.dlb.andorid.bean.Order;
import com.dlb.andorid.bean.OrderBean;
import com.dlb.andorid.bean.OrderInfo;
import com.dlb.andorid.bean.OrderInfoBean;
import com.dlb.andorid.presenter.OrderListPresenter;
import com.kwan.xframe.AppManager;
import com.kwan.xframe.common.adatper.CommonViewPageAdapter;
import com.kwan.xframe.common.widget.observablescrollview.ObservableRecyclerView;
import com.kwan.xframe.mvp.presenter.BasePresenter;
import com.kwan.xframe.mvp.view.activity.BaseCommonPageActivity;
import com.kwan.xframe.mvp.view.activity.BaseWebActivity;
import com.kwan.xframe.util.DialogFactory;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.autolayout.AutoLinearLayout;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

public class OrderActivity extends BaseCommonPageActivity implements ViewPager.OnPageChangeListener, OnRefreshListener, OnLoadMoreListener, XContract.IOrderView, BaseQuickAdapter.OnItemChildClickListener {


	//1全部，2待支付，3待收货，4售后/退款，5待评价，6已完成
	protected String[] tits = new String[]{"全部", "待支付", "待收货", "待评价", "售后/退款", "已完成"};

	@Override
	protected String getTitleTxt() {
		return "我的订单";
	}

	private OrderListPresenter mPresenter;

	@Override
	protected BasePresenter getBasePresenter() {
		mPresenter = new OrderListPresenter(this);
		return mPresenter;
	}

	@Override
	protected void initViews() {
		super.initViews();
		setRecycle();
		mViewPager.addOnPageChangeListener(this);
	}

	@Override
	protected void initData() {
		super.initData();

		if (getIntentData("index") != null) {
			int index = (int) getIntentData("index");
			mViewPager.setCurrentItem(index);
		} else {
			mPresenter.getOrderList(0);
		}

	}

	private SmartRefreshLayout sl_all, sl_dzf, sl_dsh, sl_dpj, sl_sh, sl_wc;
	private ObservableRecyclerView rv_all, rv_dzf, rv_dsh, rv_dpj, rv_sh, rv_wc;
	private OrderAdapter mAllAdapter, mDzfAdapter, mDshAdapter, mDpjAdapter, mShAdapter, mWcAdapter;

	private List<OrderBean> mAllData = new ArrayList<>();
	private List<OrderBean> mDzfData = new ArrayList<>();
	private List<OrderBean> mDshData = new ArrayList<>();
	private List<OrderBean> mDpjData = new ArrayList<>();
	private List<OrderBean> mShData = new ArrayList<>();

	private List<OrderBean> mWcData = new ArrayList<>();


	private void setRecycle() {

		View view_all = getLayoutInflater().inflate(R.layout.layout_base_recycle, null);
		View view_dzf = getLayoutInflater().inflate(R.layout.layout_base_recycle, null);
		View view_dsh = getLayoutInflater().inflate(R.layout.layout_base_recycle, null);
		View view_dpj = getLayoutInflater().inflate(R.layout.layout_base_recycle, null);
		View view_sh = getLayoutInflater().inflate(R.layout.layout_base_recycle, null);
		View view_wc = getLayoutInflater().inflate(R.layout.layout_base_recycle, null);


		sl_all = view_all.findViewById(R.id.refreshLayout);
		sl_dzf = view_dzf.findViewById(R.id.refreshLayout);
		sl_dsh = view_dsh.findViewById(R.id.refreshLayout);
		sl_dpj = view_dpj.findViewById(R.id.refreshLayout);
		sl_sh = view_sh.findViewById(R.id.refreshLayout);
		sl_wc = view_wc.findViewById(R.id.refreshLayout);


		sl_all.setEnableLoadMore(false);
		sl_all.setEnableRefresh(false);

		sl_dzf.setEnableLoadMore(false);
		sl_dzf.setEnableRefresh(false);

		sl_dsh.setEnableLoadMore(false);
		sl_dsh.setEnableRefresh(false);

		sl_dpj.setEnableLoadMore(false);
		sl_dpj.setEnableRefresh(false);

		sl_sh.setEnableLoadMore(false);
		sl_sh.setEnableRefresh(false);

		sl_wc.setEnableLoadMore(false);
		sl_wc.setEnableRefresh(false);

		sl_all.setOnLoadMoreListener(this);
		sl_dzf.setOnLoadMoreListener(this);
		sl_dsh.setOnLoadMoreListener(this);
		sl_dpj.setOnLoadMoreListener(this);
		sl_sh.setOnLoadMoreListener(this);
		sl_wc.setOnLoadMoreListener(this);

		sl_all.setOnRefreshListener(this);
		sl_dzf.setOnRefreshListener(this);
		sl_dsh.setOnRefreshListener(this);
		sl_dpj.setOnRefreshListener(this);
		sl_sh.setOnRefreshListener(this);
		sl_wc.setOnRefreshListener(this);


		rv_all = view_all.findViewById(R.id.recycleView);
		rv_dzf = view_dzf.findViewById(R.id.recycleView);
		rv_dsh = view_dsh.findViewById(R.id.recycleView);
		rv_dpj = view_dpj.findViewById(R.id.recycleView);
		rv_sh = view_sh.findViewById(R.id.recycleView);
		rv_wc = view_sh.findViewById(R.id.recycleView);

		initRecycler(rv_all);
		initRecycler(rv_dzf);
		initRecycler(rv_dsh);
		initRecycler(rv_dpj);
		initRecycler(rv_sh);
		initRecycler(rv_wc);

		mAllAdapter = new OrderAdapter(mAllData);
		mDzfAdapter = new OrderAdapter(mDzfData);
		mDshAdapter = new OrderAdapter(mDshData);
		mDpjAdapter = new OrderAdapter(mDpjData);
		mShAdapter = new OrderAdapter(mShData);
		mWcAdapter = new OrderAdapter(mWcData);

		mAllAdapter.setOnItemChildClickListener(this);
		mDzfAdapter.setOnItemChildClickListener(this);
		mDshAdapter.setOnItemChildClickListener(this);
		mDpjAdapter.setOnItemChildClickListener(this);
		mShAdapter.setOnItemChildClickListener(this);
		mWcAdapter.setOnItemChildClickListener(this);

		rv_all.setAdapter(mAllAdapter);
		rv_dzf.setAdapter(mDzfAdapter);
		rv_dsh.setAdapter(mDshAdapter);
		rv_dpj.setAdapter(mDpjAdapter);
		rv_sh.setAdapter(mShAdapter);
		rv_wc.setAdapter(mWcAdapter);


		ArrayList<View> vs = new ArrayList<>();
		vs.add(view_all);
		vs.add(view_dzf);
		vs.add(view_dsh);
		vs.add(view_dpj);
		vs.add(view_sh);
		vs.add(view_wc);

		List<String> titles = Arrays.asList(tits);
		setUpViewPage(new CommonViewPageAdapter<>(vs, titles), false, 18, getResources().getColor(R.color.colorPrimary), Color.BLACK);
	}

	private void initRecycler(RecyclerView recyclerView) {

		recyclerView.setLayoutManager(new LinearLayoutManager(this));
		recyclerView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		recyclerView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		recyclerView.setHasFixedSize(true);
		recyclerView.setItemAnimator(null);
		recyclerView.setNestedScrollingEnabled(false);

	}

	@Override
	protected int getBackGroundColor() {
		return getResources().getColor(R.color.divider_color);
	}

	@Override
	public String getPageName() {
		return null;
	}

	@Override
	public void onPageScrolled(int i, float v, int i1) {

	}

	//"全部", "待支付", "待收货", "待评价", "售后/退款"

	//1全部，2待支付，3待收货，4售后/退款，5待评价，6已完成
	@Override
	public void onPageSelected(int i) {

		switch (i) {
			case 0:
				//if (mAllData.size() == 0)
				mPresenter.getOrderList(0);
				break;
			case 1:
				//if (mDzfData.size() == 0)
				mPresenter.getOrderList(1);
				break;
			case 2:
				//if (mDshData.size() == 0)
				mPresenter.getOrderList(2);
				break;
			case 3:
				//if (mDpjData.size() == 0)
				mPresenter.getOrderList(3);
				break;
			case 4:
				//if (mShData.size() == 0)
				mPresenter.getOrderList(4);
				break;
			case 5:
				//if (mWcData.size() == 0)
				mPresenter.getOrderList(5);
				break;

		}

	}

	@Override
	public void onPageScrollStateChanged(int i) {

	}

	@Override
	public void onRefresh(@NonNull RefreshLayout refreshLayout) {

	}

	@Override
	public void onLoadMore(@NonNull RefreshLayout refreshLayout) {

	}


	int mCurrentShowType;

	//1全部，2待支付，3待收货，4售后/退款，5待评价，6已完成
	@Override
	public void getOrderListSuccess(List<OrderBean> data, int type) {
		mCurrentShowType = type;
		Log.e("kwan", "getOrderListSuccess:" + mCurrentShowType);
		switch (type) {
			case 0:

				mAllData.clear();
				mAllData.addAll(data);
				mAllAdapter.notifyDataSetChanged();
				rv_all.setAdapter(mAllAdapter);
				break;
			case 1:

				mDzfData.clear();
				mDzfData.addAll(data);
				mDzfAdapter.notifyDataSetChanged();
				rv_dzf.setAdapter(mDzfAdapter);

				break;
			case 2:
				mDshData.clear();
				mDshData.addAll(data);
				mDshAdapter.notifyDataSetChanged();
				rv_dsh.setAdapter(mDshAdapter);
				break;
			case 3:
				mShData.clear();
				mShData.addAll(data);
				mShAdapter.notifyDataSetChanged();
				rv_sh.setAdapter(mShAdapter);
				break;
			case 4:
				mDpjData.clear();
				mDpjData.addAll(data);
				mDpjAdapter.notifyDataSetChanged();
				rv_dpj.setAdapter(mDpjAdapter);
				break;
			case 5:
				mWcData.clear();
				mWcData.addAll(data);
				mWcAdapter.notifyDataSetChanged();
				rv_wc.setAdapter(mWcAdapter);
				break;
		}

	}


	public class OrderAdapter extends BaseQuickAdapter<OrderBean, BaseViewHolder> {

		public OrderAdapter(@Nullable List<OrderBean> data) {
			super(R.layout.list_item_order, data);
		}

		@Override
		protected void convert(BaseViewHolder helper, OrderBean item) {

			helper.setText(R.id.tv_num, "共" + item.getOrder_num() + "件商品 实付：");
			helper.setText(R.id.tv_price, "¥" + item.getTotal_fee());

			AutoLinearLayout container = helper.getView(R.id.ll_container);

			helper.getView(R.id.ll_state_dzf).setVisibility(View.GONE);
			helper.getView(R.id.ll_state_dsh).setVisibility(View.GONE);
			helper.getView(R.id.ll_state_shtk).setVisibility(View.GONE);
			helper.getView(R.id.ll_state_dpj).setVisibility(View.GONE);

			switch (item.getOrder_type()) {
				case 1://待支付
					helper.setVisible(R.id.ll_state_dzf, true);
					break;
				case 2://待收货
					helper.setVisible(R.id.ll_state_dsh, true);
					break;
				case 3://售后退款
					helper.setVisible(R.id.ll_state_shtk, true);

					if (item.getOrder_type_status() == 1) {
						helper.setText(R.id.tv_state_shtk, "退款中");
						helper.setTextColor(R.id.tv_state_shtk, getResources().getColor(R.color.color_orange));
					} else if (item.getOrder_type_status() == 2) {
						helper.setText(R.id.tv_state_shtk, "已退款");
						helper.setTextColor(R.id.tv_state_shtk, getResources().getColor(R.color.txt_gray));
					}
					break;
				case 4:
					helper.setVisible(R.id.ll_state_dpj, true);
					break;
			}

			helper.addOnClickListener(R.id.tv_pay);
			helper.addOnClickListener(R.id.tv_delete);
			helper.addOnClickListener(R.id.tv_tk);
			helper.addOnClickListener(R.id.tv_pj);


			for (OrderInfoBean info : item.getInfo()) {
				View view = LayoutInflater.from(OrderActivity.this).inflate(R.layout.list_item_order_product, null);
				((TextView) view.findViewById(R.id.tv_name)).setText(info.getName());
				((TextView) view.findViewById(R.id.tv_price)).setText(info.getSale_price());
				mImageLoader.loadUrl(info.getPic(), (ImageView) view.findViewById(R.id.iv_icon));
				container.addView(view);
			}

		}
	}


	@Override
	public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

		List<OrderBean> data = null;

		switch (mCurrentShowType) {
			case 0:
				data = mAllData;
				break;
			case 1:
				data = mDzfData;
				break;
			case 2:
				data = mDshData;
				break;
			case 3:
				data = mShData;
				break;
			case 4:
				data = mDpjData;
				break;
			case 5:
				data = mWcData;
				break;
		}

		if (data == null) {
			return;
		}

		OrderBean orderBean = data.get(position);

		switch (view.getId()) {

			case R.id.tv_delete:
				showSureDialog(orderBean, position, R.id.tv_delete);
				break;
			case R.id.tv_pay:
				showProgress("");
				mPresenter.getOrderInfo(orderBean.getOrder_no());
				break;
			case R.id.tv_tk:
				showSureDialog(orderBean, position, R.id.tv_tk);
				break;
			case R.id.tv_pj:
				showProgress("");
				mPresenter.pjOrder(orderBean.getOrder_id(), orderBean.getOrder_no(), position);
				break;

		}

	}

	@Override
	public void pjOrderSuccess(XServerMsg data, Integer index) {
		dismissProgress();
		if (data.getCode() == 0) {

			Bundle bundle = new Bundle();
			bundle.putString("url", data.getMsg());
			bundle.putString("title", "评价");
			bundle.putInt("mode", BaseWebActivity.MODE_WEB);
			go2Activity(WebActivity.class, bundle, false);

		} else {
			toastMsg(data.getMsg());
		}
	}

	@Override
	public void getOrderInfoSuccess(XServerMsg<OrderInfo> data) {
		dismissProgress();
		if (data.getCode() == 0) {

			Bundle bundle = new Bundle();

			//2020-01-13 16:37:40
			OrderInfo orderInfo = data.getData();
			Date date1;
			SimpleDateFormat simdate1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String str1 = orderInfo.getAddress_time();
			try {
				date1 = simdate1.parse(str1);

				Order order = new Order();
				order.setAddress_time(date1.getTime());
				order.setCommodity_data(orderInfo.getCommodity_data());
				order.setCoupon_num(orderInfo.getCoupon_num());
				order.setIntegral_num(orderInfo.getIntegral_num());
				order.setOrder_id(orderInfo.getOrder_id());
				order.setTotal_commodity_num(orderInfo.getTotal_commodity_num());
				order.setOrder_no(orderInfo.getOrder_no());
				order.setTotal_sale_price(orderInfo.getTotal_sale_price());

				bundle.putSerializable("order", order);
				go2Activity(OrderSureActivity.class, bundle, false);
			} catch (ParseException e) {
				toastMsg("日期错误");
				e.printStackTrace();
			}


		} else {
			toastMsg(data.getMsg());
		}
	}

	protected WebView tbsWebView;

	protected void loadWeb(String loadUrl) {

		tbsWebView = new WebView(this);
		WebSettings settings = tbsWebView.getSettings();
		settings.setJavaScriptEnabled(true);
		//https与http混合资源处理
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			settings.setMixedContentMode(android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
		}
		// 设置加载进来的页面自适应手机屏幕
		settings.setUseWideViewPort(true);
		settings.setLoadWithOverviewMode(true);
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		settings.setDisplayZoomControls(true);
		settings.setDefaultTextEncodingName("UTF-8");
		settings.setJavaScriptCanOpenWindowsAutomatically(true);

		//settings.setUserAgent( );
		final String Referer = "http://www.dilinbang.com";
		tbsWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
		tbsWebView.setWebViewClient(new WebViewClient() {

			@Override
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
			}

			@Override
			public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
				super.onReceivedHttpError(view, request, errorResponse);
			}

			@Override
			public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
				handler.proceed();  // 接受所有网站的证书
				super.onReceivedSslError(view, handler, error);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.e("kwan", "shouldOverrideUrlLoading:" + url);
				if (url.startsWith("weixin://wap/pay?")) {
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(url));
					startActivityForResult(intent, 200);
					return true;
				} else {
					Map<String, String> extraHeaders = new HashMap<>();
					extraHeaders.put("Referer", Referer);
					view.loadUrl(url, extraHeaders);
					return true;
				}
			}
		});
		//需要添加到支付链接的请求头
		//String targetUrl=";  //后台返回的支付链接

		Map<String, String> extraHeaders = new HashMap<>();
		extraHeaders.put("Referer", Referer);
		tbsWebView.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
			}

		});

		tbsWebView.loadUrl(loadUrl, extraHeaders);

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.e("kwan", "onActivityResult");

		if (requestCode == 200) {

			View view = getLayoutInflater().inflate(R.layout.dialog_pay_result, null);
			final Dialog dialog = DialogFactory.showCustomDialog3(this, view);
			view.findViewById(R.id.tv_pay_ok).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					finish();
				}
			});

			view.findViewById(R.id.tv_kf).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
					go2Activity(KfActivity.class, null, false);
					finish();
				}
			});

			dialog.show();
		}
	}

	public void showSureDialog(final OrderBean orderBean, final int index, final int id) {
		View view = getLayoutInflater().inflate(com.kwan.xframe.R.layout.layout_common_dialog, null);
		final Dialog dialog = DialogFactory.showCustomDialog3(AppManager.getAppManager().currentActivity(), view);

		String str = "";
		String strBtn = "确定";

		switch (id) {
			case R.id.tv_delete:
				str = "是否删除此订单";
				strBtn = "删除";
				break;
			case R.id.tv_tk:
				str = "是否申请退款";
				strBtn = "退款";
				break;
		}

		((TextView) view.findViewById(com.kwan.xframe.R.id.tv_msg)).setText(str);
		((TextView) view.findViewById(com.kwan.xframe.R.id.tv_ok)).setText(strBtn);

		view.findViewById(com.kwan.xframe.R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				showProgress("");

				switch (id) {
					case R.id.tv_delete:
						mPresenter.delOrder(orderBean.getOrder_id(), orderBean.getOrder_no(), index);
						break;
					case R.id.tv_tk:
						mPresenter.tkOrder(orderBean.getOrder_id(), orderBean.getOrder_no(), index);
						break;
				}

				dialog.dismiss();
			}
		});
		view.findViewById(com.kwan.xframe.R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
	}

	@Override
	public void tkOrderSuccess(XServerMsg data, Integer index) {

		mDshAdapter.remove(index);
		rv_dsh.setAdapter(mDshAdapter);
		dismissProgress();
		toastMsg(data.getMsg());

	}

	@Override
	public void delOrderSuccess(XServerMsg data, int index) {
		Log.e("kwan", "delOrderSuccess mCurrentShowType:" + mCurrentShowType);
		dismissProgress();
		toastMsg(data.getMsg());
		if (data.getCode() == 0) {
			switch (mCurrentShowType) {
				case 0:

					mAllAdapter.remove(index);
					//mAllData.remove(index);
					break;
				case 1:
					mDzfAdapter.remove(index);
					//mDzfData.remove(index);
					break;
				case 2:

					mDshAdapter.remove(index);
					//mDshData.remove(index);
					break;
				case 3:

					mShAdapter.remove(index);
					//mShData.remove(index);
					break;
				case 4:

					mDpjAdapter.remove(index);
					//mDpjData.remove(index);
					break;
				case 5:

					mWcAdapter.remove(index);
					//mWcData.remove(index);
					break;
			}
		}
	}
}
